﻿@{
    ViewBag.Title = "My borrowings";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@if (User != null)
{
    <div id="PresentationBox">
        <h2 class="centeredHeaderText">My borrowings</h2>

        <table class="DataPresentationtable" id="myBorrowings">
            <tr>
                <td><center><img src="/Content/images/loading.gif" />loading data...</center></td>
            </tr>
        </table>
        <br/>
        <h2 class="centeredHeaderText">My reservations</h2>

        <table class="DataPresentationtable" id="myReservations">
            <tr>
                <td><center><img src="/Content/images/loading.gif" />loading data...</center></td>
            </tr>
        </table>
    </div>


    <script type="text/javascript">

    var dataSetBorrowings = [];
    var dataSetReservations = [];

    $(document).ready(function () {
        $.ajax({
            url: "/api/loan/",
            type: "GET",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", getAuthorizationHeader('@User.UserId', ''));
            },
            dataType: "json"
        }).done(function (data) {
                console.log(data);
                $.each(data, function (key, val) {
                    console.log(val);

                    var loan = [];

                    loan.Title = "<a href='/Title/Get/" + val.Loanable.Title.TitleId + "'>" + val.Loanable.Title.BookTitle + "</a>";
                    loan.Barcode = val.Loanable.Barcode;
                    if (val.RecallExpiredDate != null)
                    	loan.RecallExpiredDate = val.RecallExpiredDate.split("T").splice(0, 1);
                    else
                    	loan.RecallExpiredDate = "Not Recalled";
                    loan.Location = val.Loanable.Location + "(" + val.Loanable.Category.Name + ")";
                    loan.ToBeReturnedDate = val.ToBeReturnedDate.split("T").splice(0, 1);
                    loan.CheckInBtn = '<input type="button" class=\"checkInOutBtn\" value="Check in" onClick="checkInLoanable(' + val.LoanId + ')"/>'
                    dataSetBorrowings.push(loan);
                });

                $('#myBorrowings').DataTable({
                    "bFilter": false,
                    "fnDrawCallback": function () {
                        if (Math.ceil((this.fnSettings().fnRecordsDisplay()) / this.fnSettings()._iDisplayLength) > 1) {
                            $('#myBorrowings_paginate').css("display", "block");
                        } else {
                            $('#myBorrowings_paginate').css("display", "none");
                        }
                    },
                    "data": dataSetBorrowings,
                    "columns": [
                        { "data": "Title", "title": "Title", "sWidth": "40%" },
                        { "data": "Barcode", "title": "DoeLibS-ID", "sWidth": "15%" },
                        { "data": "Location", "title": "Location", "sWidth": "30%" },
                        { "data": "RecallExpiredDate", "title": "Recall expire date", "sWidth": "15%" },
						{ "data": "CheckInBtn", "title": "" }
                    ]
                });

                //remove ugly DataTable css
                $('#myBorrowings').removeClass("dataTable");
            });

            $.ajax({
                url: '/api/reservation/',
                type: 'GET',
                dataType: 'json',
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("Authorization", getAuthorizationHeader('@User.UserId', ''));
                }
            }).done(function (data) {
                console.log(data);
                $.each(data, function (key, val) {
                    console.log(val);

                    var reservation = [];

                    reservation.Title = "<a href='/Title/Get/" + val.Title.TitleId + "'>" + val.Title.BookTitle + "</a>";
                    reservation.ReserveDate = val.ReserveDate.split("T").splice(0, 1);
                    //reservation.id = val.Loanable.Barcode;

                    if (val.LoanRecalled) {
                        var availableDate = new Date(val.AvailableDate.split("T").splice(0, 1));
                        var pickUpDate = new Date();
                        pickUpDate.setDate(availableDate.getDate() + 7);

                        reservation.Status = "Available for you. Pickup till " + pickUpDate.toLocaleDateString();
                    	//reservation.CheckOutBtn = '<input type="button" class=\"checkInOutBtn\" value="Check out" onClick="checkOutLoanable(' + val.LoanRecalled.loanableId + ')"/>'
                    } else {
                    	reservation.Status = "waiting for loanable";
                    	//reservation.CheckOutBtn = "";
                    }

                    dataSetReservations.push(reservation);
                });

                $('#myReservations').DataTable({
                    "bFilter": false,
                    "fnDrawCallback": function () {
                        if (Math.ceil((this.fnSettings().fnRecordsDisplay()) / this.fnSettings()._iDisplayLength) > 1) {
                            $('#myReservations_paginate').css("display", "block");
                        } else {
                            $('#myReservations_paginate').css("display", "none");
                        }
                    },
                    "data": dataSetReservations,
                    "columns": [
                        { "data": "Title", "title": "Title", "sWidth": "40%" },
                        { "data": "Status", "title": "Status", "sWidth": "35%" },
                        { "data": "ReserveDate", "title": "Reservation date", "sWidth": "25%" },
						//{ "data": "CheckOutBtn", "title": "" }
                    ]
                });

                //remove ugly DataTable css
                $('#myReservations').removeClass("dataTable");
            });

    });

    	function checkInLoanable(loanId) {
    		console.log("checkIn loanable with id " + loanId);

    		$.ajax({
    			url: "/api/loan/" + loanId,
    			type: "DELETE",
    			beforeSend: function (xhr) {
    				xhr.setRequestHeader("Authorization", getAuthorizationHeader('@User.UserId', ''));
					}
    		}).done(function () {
    			setHttpMessage("Loanable checked in", true);
				location.reload();
			}).fail(function () {
				setHttpMessage("Technical problems, please try again", false);
				location.reload();
			});
    	}

    	@*function checkOutLoanable(loanableId) {
    		console.log("checkOut loanable with id " + loanableId);

    		$.ajax({
    			url: "/api/loanable/" + loanableId,
    			type: "POST",
    			beforeSend: function (xhr) {
    				xhr.setRequestHeader("Authorization", getAuthorizationHeader('@User.UserId', ''));
    			}
    		}).done(function () {
    			setHttpMessage("Loanable checked out", true);
    			location.reload();
    		}).fail(function () {
    			setHttpMessage("Technical problems, please try again", false);
    			location.reload();
    		});
			}*@

    </script>
}